"""Provides the FileObserver class."""
import time
import os
from PyQt4.QtCore import *
import threading
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from watchdog.events import FileSystemEventHandler

class FileObserver(Observer, FileSystemEventHandler, QObject):
    """Watches for changes in a list of files.
    
    Emits a FileChanged signal when the one of the registered files changed."""
    # Number of seconds between signals
    minInterval = 1
    
    FileChanged = pyqtSignal(list)
    
    def __init__(self, filenames=[], *arg, **kwargs):
        Observer.__init__(self)
        FileSystemEventHandler.__init__(self)
        QObject.__init__(self)
        self.name = "File Observer"

        path = "."
        self.schedule(self, path, recursive=False)

        self.tic = -1
        self.changedFilenames = []
        self.L = threading.Lock() # To prevent reading and writing to filenames
                                  # simultaneously
        self.SetFilenames(filenames)
        
    def SetFilenames(self, filenames):
        with self.L:
            self.filenames = filenames
        
    def on_any_event(self, event):
        with self.L:
            theCase = os.path.basename(event.src_path)
            if theCase in self.filenames and not theCase in self.changedFilenames:
                self.changedFilenames.append(theCase)

            if len(self.changedFilenames) > 0:
                t = time.time()
                if self.tic == -1 or t-self.tic >= self.minInterval:
                    self.FileChanged.emit(self.changedFilenames)
                    self.tic = t # Resets time break
                    self.changedFilenames = [] # Resets list of changed files

    def Exit(self):
        self.stop()

